<template>
  <div class="page-content attraction-edit">
    <div class="mb-6 flex justify-between items-center">
      <div>
        <h1 class="text-2xl font-bold">{{ isEdit ? '编辑设施' : '添加设施' }}</h1>
      </div>
      <el-button @click="goBack">
        <el-icon> <Back /> </el-icon>返回
      </el-button>
    </div>

    <el-card shadow="hover">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="top"
        status-icon
        require-asterisk-position="right"
        scroll-to-error
      >
        <el-row :gutter="20">
          <!-- 基本信息 -->
          <el-col :span="24">
            <div class="form-section-title mb-4">
              <h2 class="text-lg font-medium">基本信息</h2>
              <div class="form-section-line"></div>
            </div>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="设施名称" prop="facilityName">
              <el-input v-model="form.facilityName" placeholder="请输入设施名称" />
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="英文名称" prop="facilityEnglishName">
              <el-input v-model="form.facilityEnglishName" placeholder="请输入英文名称" />
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="拼音名称" prop="facilityPinyinName">
              <el-input v-model="form.facilityPinyinName" placeholder="请输入拼音名称" />
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="位置名称" prop="location">
              <div class="flex items-center w-full">
                <div class="flex-1">
                  <el-input v-model="form.location" placeholder="请选择位置" />
                </div>
                <el-button class="ml-2" @click="openMapSelection">
                  <el-icon>
                    <Location />
                  </el-icon>
                </el-button>
              </div>
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="所属景区">
              <!-- <el-autocomplete
                v-model="beLong"
                placeholder="请输入所属景区" 
                :fetch-suggestions="getBelongId"
                @select="handleSelect"
              /> -->
              <el-select v-model="form.belongId" filterable placeholder="请选择或输入搜索所属景区">
                <el-option
                  v-for="item in searchResults"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="状态" prop="operationStatus">
              <el-select v-model="form.operationStatus" placeholder="请选择状态" class="w-full">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="开放开始时间" prop="openStartTime">
              <el-time-picker
                v-model="form.openStartTime"
                placeholder="选择时间"
                class="w-full!"
                format="HH:mm:ss"
                value-format="HHmmss"
              />
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="开放结束时间" prop="openEndTime">
              <el-time-picker
                v-model="form.openEndTime"
                placeholder="选择时间"
                class="w-full!"
                format="HH:mm:ss"
                value-format="HHmmss"
              />
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="开放周期" prop="openWeek">
              <el-select
                v-model="form.openWeek"
                multiple
                placeholder="请选择开放周期"
                class="w-full!"
              >
                <el-option label="星期一" :value="1" />
                <el-option label="星期二" :value="2" />
                <el-option label="星期三" :value="3" />
                <el-option label="星期四" :value="4" />
                <el-option label="星期五" :value="5" />
                <el-option label="星期六" :value="6" />
                <el-option label="星期日" :value="7" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="占地面积" prop="floorSpace">
              <el-input v-model="form.floorSpace" placeholder="例如: 15000">
                <template #append>m²</template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="建成时间" prop="buildData">
              <el-date-picker
                v-model="form.buildData"
                type="date"
                placeholder="选择日期"
                class="w-full!"
                value-format="YYYYMMDD"
              />
            </el-form-item>
          </el-col>

          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="设施类型" prop="facilityType">
              <el-select
                v-model="form.facilityType"
                placeholder="请选择设施类型"
                class="w-full!"
                popper-class="facility-type-popper"
              >
                <el-option
                  v-for="item in facilityTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                  <div class="flex items-center">
                    <img :src="item.dictRemark" class="w-4 h-4 mr-2" />
                    <span>{{ item.label }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="适用人群" prop="applyUser">
              <el-select v-model="form.applyUser" placeholder="全部" class="w-full!">
                <el-option
                  v-for="item in applyUserOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="选择设施图标" prop="icon">
              <ArtIconSelector
              :iconType="IconTypeEnum.CLASS_NAME"
              @getIcon="getIcon"
              width="356px"
              defaultIcon="iconsys-baitianmoshi3"
              />
          </el-form-item>
          </el-col> -->

          <el-col :span="24">
            <el-form-item label="设施介绍" prop="introduce">
              <el-input
                v-model="form.introduce"
                type="textarea"
                :rows="4"
                :maxlength="500"
                placeholder="请输入设施详细介绍"
              />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="24">
            <el-form-item label="设施公告" >
              <el-input
                v-model="form.announcement"
                type="textarea"
                :rows="4"
                :maxlength="500"
                placeholder="请输入设施的公告信息"
              />
            </el-form-item>
          </el-col> -->

          <!-- 图片管理 -->
          <el-col :span="24" class="mt-4">
            <div class="form-section-title mb-4">
              <h2 class="text-lg font-medium">图片管理</h2>
              <div class="form-section-line"></div>
            </div>
          </el-col>

          <el-col :span="24">
            <el-form-item label="主图" prop="imageUrl">
              <div class="w-full">
                <MyUpload
                  :file-list="fileList"
                  @deleteFile="deleteFile"
                  @uploadFileSuccess="success"
                />
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="轮播图片">
              <div class="w-full">
                <MyUpload
                  :file-list="sildeFileList"
                  @deleteFile="slideDeleteFile"
                  @uploadFileSuccess="slideSuccessFile"
                />
              </div>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="24">
            <el-form-item label="特色标签" prop="featureTag">
              <el-input v-model="form.featureTag" type="textarea" :rows="2" placeholder="请输入设施特色标签，多个标签用逗号分隔" />
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="信息标签" prop="messageGambit">
              <div class="tags-container">
                <el-tag
                  v-for="tag in tags"
                  :key="tag"
                  class="tag-item"
                  closable
                  @close="handleClose(tag)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  v-if="inputVisible"
                  ref="InputRef"
                  v-model="inputValue"
                  class="tag-input"
                  size="small"
                  @keyup.enter="handleInputConfirm"
                  @blur="handleInputConfirm"
                />
                <el-button v-else class="button-new-tag" size="small" @click="showInput">
                  <el-icon>
                    <Plus />
                  </el-icon>
                  添加标签
                </el-button>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="2"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="form-actions mt-6 flex justify-end">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="submitForm" v-loading="loading" :disabled="loading"
            >保存</el-button
          >
        </div>
      </el-form>
    </el-card>
    <MapSelection
      v-model="mapVisible"
      :center="{
        lng: 114.17842233364557,
        lat: 30.506250728187435
      }"
      ref="mapSelectionRef"
      @confirm="handleMapConfirm"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, nextTick, onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElMessage, FormInstance, FormRules } from 'element-plus'
  import { Back } from '@element-plus/icons-vue'
  import { scenicScenicSpotPageScenicSpotUsingPost } from '@/api/4a/jingdi'
  import MapSelection from '@/components/mapSelection/index.vue'
  import { arrayToStr, strToArray } from '@/utils/utils'
  import {
    dictApiListDictByTypeUsingPost,
    scenicScenicSpotFacilityGetScenicSpotFacilityUsingPost,
    scenicScenicSpotFacilitySaveScenicSpotFacilityUsingPost
  } from '@/api/4a'
  import { useWorktabStore } from '@/store/modules/worktab'
  const worktabStore = useWorktabStore()
  const route = useRoute()
  const router = useRouter()
  const formRef = ref<FormInstance>()
  const facilityId = ref(route.query.id ? route.query.id : undefined)
  const isEdit = computed(() => !!facilityId.value)
  const loading = ref(false)
  // 获取所属景点相关
  const searchResults = ref([])
  // 获取设施类型相关
  const facilityTypeOptions = ref([])
  // 获取适用人群相关
  const applyUserOptions = ref([])
  // 状态选项
  const statusOptions = [
    { label: '开放中', value: 1 },
    { label: '部分维修', value: 2 },
    { label: '维护中', value: 3 },
    { label: '已关闭', value: 4 }
  ]

  // 标签相关变量
  const tags = ref<string[]>([]) // 标签数组
  const inputVisible = ref(false) // 输入框是否可见
  const inputValue = ref('') // 输入框值
  const InputRef = ref() // 输入框引用

  // 表单初始数据
  const initialForm = {
    belongId: undefined, // 所属ID =
    belongType: 1, // 所属类型
    buildData: '', // 建成时间 =
    facilityType: undefined, // 设施类型
    applyUser: undefined, // 适用人群
    contactPerson: 0, // 负责人员id /
    responsibleDept: 0, // 负责人部门id /
    facilityEnglishName: '', // 设施英文名称=
    facilityName: '', // 设施名称=
    facilityPinyinName: '', // 设施拼音名称=
    featureTag: '', // 设施特色标签 =
    floorSpace: '', // 占地面积=
    galleryImages: '[]', // 相册图片
    id: undefined, // id
    imageUrl: '[]', // 主要图片 =
    introduce: '', // 设施介绍 =
    location: '', // 设施位置 =
    locationDescription: '', // 设施位置描述 /
    locationJson: '', // 设施位置经纬
    locationName: '', // 设施位置描述 /
    openEndTime: '', // 开放结束时间 =
    openStartTime: '', // 开放开始时间 =
    openWeek: '', // 开放周 =
    operationStatus: '', // 运营状态状态
    remark: '', // 备注
    sildeshowImg: '[]' // 轮播图
  }

  // 表单数据
  const form = reactive({ ...initialForm })

  // 将标签处理为括号形式
  const processTagsWithBrackets = (tagString: string): string[] => {
    if (!tagString) return []
    // 匹配括号中的内容
    const regex = /\(([^)]+)\)/g
    const matches = tagString.match(regex)
    if (!matches) return [tagString]
    // 提取括号中的内容
    return matches.map((tag) => tag.slice(1, -1))
  }

  // 将标签转换回字符串格式
  const convertTagsToString = (tagsArray: string[]): string => {
    return tagsArray.map((tag) => `(${tag})`).join('')
  }

  // 显示输入框
  const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
      InputRef.value?.input?.focus()
    })
  }

  // 添加标签
  const handleInputConfirm = () => {
    if (typeof inputValue.value === 'string' && inputValue.value.trim()) {
      if (!tags.value.includes(inputValue.value)) {
        tags.value.push(inputValue.value)
      }
    }
    inputVisible.value = false
    inputValue.value = ''
  }

  // 删除标签
  const handleClose = (tag: string) => {
    const index = tags.value.indexOf(tag)
    if (index > -1) {
      tags.value.splice(index, 1)
    }
  }

  // 验证函数
  const validatePass = (rule: any, value: any, callback: any) => {
    if (value && form.locationJson) {
      callback()
    } else {
      callback(new Error('请选择设施位置'))
    }
  }

  // 表单验证规则
  const rules = reactive<FormRules>({
    facilityName: [
      { required: true, message: '请输入设施名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    operationStatus: [{ required: true, message: '请选择设施状态', trigger: 'change' }],
    introduce: [
      { required: true, message: '请输入设施介绍', trigger: 'blur' },
      { min: 10, message: '介绍不能少于10个字符', trigger: 'blur' }
    ],
    imageUrl: [
      { required: true, message: '请选择封面图片', trigger: 'change' },
      {
        validator: (rule, value) => {
          let list = []

          try {
            list = typeof value === 'string' ? JSON.parse(value) : value
          } catch {
            list = []
          }

          if (!Array.isArray(list) || list.length === 0) {
            throw new Error('请上传至少一张封面图片')
          }

          return Promise.resolve()
        },
        trigger: 'change'
      }
    ],
    openWeek: [{ required: true, message: '请选择开放周期', trigger: 'change' }],
    buildData: [{ required: true, message: '请选择建成时间', trigger: 'change' }],
    floorSpace: [{ required: true, message: '请输入占地面积', trigger: 'blur' }],
    location: [{ validator: validatePass, trigger: 'blur' }],
    facilityType: [{ required: true, message: '请选择设施类型', trigger: 'change' }],
    applyUser: [{ required: true, message: '请选择适用人群', trigger: 'change' }],
    icon: [{ required: true, message: '请选择图标', trigger: 'change' }]
  })

  // 首图
  const fileList = computed({
    get() {
      return JSON.parse(form.imageUrl || '[]')
    },
    set(value) {
      form.imageUrl = value
    }
  })

  const success = (a) => {
    fileList.value.push(a.data)
    fileList.value = JSON.stringify(fileList.value)
    formRef.value?.validateField('imageUrl')
  }

  const deleteFile = (params) => {
    fileList.value = JSON.stringify(fileList.value.filter((item) => item.path !== params.path))
    formRef.value?.validateField('imageUrl')
  }

  // 轮播图片
  const sildeFileList = computed({
    get() {
      return JSON.parse(form.sildeshowImg || '[]')
    },
    set(value) {
      form.sildeshowImg = value
    }
  })
  const slideSuccessFile = (a) => {
    sildeFileList.value.push(a.data)
    sildeFileList.value = JSON.stringify(sildeFileList.value)
  }

  const slideDeleteFile = (params) => {
    sildeFileList.value = JSON.stringify(
      sildeFileList.value.filter((item) => item.path !== params.path)
    )
  }

  // 提交表单
  const submitForm = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      loading.value = true
      scenicScenicSpotFacilitySaveScenicSpotFacilityUsingPost({
        body: {
          ...form,
          buildData: form.buildData,
          openWeek: arrayToStr(form.openWeek),
          locationJson: JSON.stringify(form.locationJson),
          featureTag: convertTagsToString(tags.value) // 将标签转换为字符串提交
        }
      })
        .then((res) => {
          if (res.code === 0) {
            ElMessage.success(isEdit.value ? '设施信息更新成功' : '设施添加成功')
            router.push('/facility/facility-list')
          } else {
            ElMessage.error(res.msg)
          }
        })
        .finally(() => {
          loading.value = false
        })
    } catch {
      ElMessage.error('请完善表单信息')
    }
  }

  // 返回列表
  const goBack = () => {
    Object.assign(form, initialForm) // 清空表单
    tags.value = [] // 清空标签
    fileList.value = '[]' // 清空主图
    sildeFileList.value = '[]' // 清空轮播图
    worktabStore.removeTab(route.path)
    router.replace('/facility/facility-list')
  }

  const mapSelectionRef = ref()
  // 打开地图选择
  const openMapSelection = () => {
    mapVisible.value = true
    mapSelectionRef.value.openPopup({
      lng: form.locationJson.longitude,
      lat: form.locationJson.latitude
    })
  }

  const mapVisible = ref(false)

  const handleMapConfirm = (data) => {
    // 更新位置信息
    if (data && data.point && data.surroundingPois.length > 0) {
      form.location = data.surroundingPois[0].title // 保存坐标值

      // 更新locationJson，存储完整的位置数据，兼容各个端口的字段
      form.locationJson = {
        longitude: data.point.lng, //经度
        latitude: data.point.lat, //纬度
        height: data.point.height || 0
      }

      formRef.value.validateField('location')

      mapVisible.value = false
    }
     else {
      ElMessage.error('请选择位置')
    }
    
  }

  // 获取设施详情
  const getFacilityDetail = async () => {
    const res = await scenicScenicSpotFacilityGetScenicSpotFacilityUsingPost({
      params: { scenicSpotFacilityId: facilityId.value }
    })
    if (res.code === 0) {
      const newData = {
        ...res.data,
        locationJson: JSON.parse(res.data?.locationJson || '{}'),
        openWeek: strToArray(res.data?.openWeek)
      }
      Object.assign(form, newData)
      // 回显标签
      if (form.featureTag) {
        tags.value = processTagsWithBrackets(form.featureTag)
      }
    } else {
      ElMessage.error(res.msg || '获取设施信息失败')
    }
  }

  // 匹配相关景点数据
  const getBelongId = async () => {
    const res = await scenicScenicSpotPageScenicSpotUsingPost({
      body: {
        current: 1,
        like: form.belongId,
        operationStatus: undefined,
        size: 4
      }
    })
    if (res.code === 0) {
      const results = res.data?.list.map((item) => ({
        value: item.spotName,
        id: item.id
      }))
      searchResults.value = results
    } else {
      searchResults.value = []
    }
  }

  // 获取设施类型
  const getFacilityType = async () => {
    const res = await dictApiListDictByTypeUsingPost({ body: ['95210'] })
    if (res.code === 0) {
      facilityTypeOptions.value = res.data[0].dictDataList.map((item) => ({
        label: item.dictLabel,
        value: item.dictValue,
        dictRemark: item.dictRemark
      }))
    } else {
      facilityTypeOptions.value = []
    }
  }

  // 获取适应人群
  const getAppleUser = async () => {
    const res = await dictApiListDictByTypeUsingPost({ body: ['95220'] })
    if (res.code === 0) {
      applyUserOptions.value = res.data[0].dictDataList.map((item) => ({
        label: item.dictLabel,
        value: item.dictValue
      }))
    } else {
      applyUserOptions.value = []
    }
  }

  // const getIcon = (icon: string) => {
  //   console.log(icon);
  // }
  onMounted(() => {
    getBelongId()
    getFacilityType()
    getAppleUser()
  })

  // 使用 watch 监听 id 变化
  watch(
    () => route.query.id,
    (newId) => {
      facilityId.value = newId
      // 清空状态
      searchResults.value = []

      if (newId) {
        getFacilityDetail()
      } else {
        Object.assign(form, initialForm)
        nextTick(() => {
          formRef.value?.resetFields()
        })
      }
    },
    { immediate: true }
  )
</script>

<style lang="scss" scoped>
  :deep(.el-upload-dragger) {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
  }

  .tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
    min-height: 32px;
    padding: 4px;
    background-color: var(--el-fill-color-blank);
    border: 1px solid var(--el-border-color);
    border-radius: 4px;
    transition: all 0.3s;

    &:hover {
      border-color: var(--el-color-primary);
    }
  }

  .tag-input {
    width: 120px;
    margin: 0;
    vertical-align: middle;
  }
</style>
